require('./index')

const config = require('./static/config')

let { createToastManager } = require('./static/toast')

const WXPage = require('./static/wxpage')

let Route = require('./utils/compile/route.js')

let { getLastPage, decodeQueryData, encodeQueryData } = require('./utils/compile/utils')

let { transformCitys } = require('./utils/compile/index')

const {
  OtherRegisterError,
  CreateTokenError,
  UserNotRegisterError,
} = require('./static/error')

console.d = function (...args) {
  if (config.mode === 'dev') {
    if (console.trace) {
      console.log.apply(console, args)
      console.groupCollapsed('trace')
      console.trace.apply(console, args)
      console.groupEnd()
    } else {
      console.log.apply(console, args)
    }
  }
}

let toastManager  = createToastManager()

let getProvinceCityRequest = $global.Api.makeGetRequest({
  action: '/province/city'
}, function (res, app, next) {
  next(res)
})

let getRegisterStatusRequest = $global.Api.makeGetRequest({
  action: '/register/status'
}, function (res, app, next) {
  next(res)
})


let _cacheAppOptions = {}
let _cacheScene = ''
let isFirst = false

createApp({
  onLaunch(options) {
    _cacheAppOptions = options
    getProvinceCityRequest.bind(this)

    _cacheScene = decodeURIComponent(options.query.scene || '')

    console.log('onLaunch', options, _cacheScene, decodeQueryData(_cacheScene))

    this.globalData.citys = [
      {
        "uuid": "b24d9969-fBEA-D32b-2899-dE13B693883c",
        "name": "Margaret Smith",
        "level": 0,
        "citys": [
          {
            "uuid": "cCaCCB3C-5cc2-7bb4-Ab67-Db7CCD96B8A3",
            "name": "Susan Anderson",
            "level": 1
          },
          {
            "uuid": "DC77F649-1cbc-7F3f-AcEd-DAebCAB2636C",
            "name": "Thomas Johnson",
            "level": 1
          },
          {
            "uuid": "39cF16e3-3dc6-b5Af-4AAC-B917b440f5cf",
            "name": "Paul Allen",
            "level": 1
          }
        ]
      },
      {
        "uuid": "1CE175f2-bBBa-f6f2-Aa86-cFC1EdB521a0",
        "name": "Deborah Thomas",
        "level": 0,
        "citys": [
          {
            "uuid": "09eFa027-10A1-e7d0-C3f4-7EaAC5A329f7",
            "name": "Daniel Lewis",
            "level": 1
          },
          {
            "uuid": "cC63bE92-c7d8-D5E2-9ceE-8ab3ff4D3176",
            "name": "Robert Young",
            "level": 1
          },
        ]
      },
      {
        "uuid": "766EBbbD-E6b8-AcDC-d34B-ABBBfBf93fDE",
        "name": "Larry Walker",
        "level": 0,
        "citys": [
          {
            "uuid": "973C87F7-3BaA-EFef-A6Ce-2A161Cecb97E",
            "name": "1Ronald Hernandez",
            "level": 1
          },
          {
            "uuid": "B2BED1a8-Cd06-EDbD-9F5C-28ADe02aBA3c",
            "name": "1Amy Robinson",
            "level": 1
          },
          {
            "uuid": "373d7BfC-6aEf-f2b4-Db9B-eF59B45A1BBe",
            "name": "1Nancy Miller",
            "level": 1
          },
        ]
      }
    ]

    console.log('this.globalData', this.globalData)
  },
  onShow(options) {
    console.log('onShow', options)

    if (options.query && options.query.scene) {
      _cacheScene = decodeURIComponent(options.query.scene || '')

      console.log('onShow', _cacheScene, decodeQueryData(_cacheScene))
    }
  },
  getQueryScene() {
    return decodeQueryData(_cacheScene)
  },
  getLaunchOptionsSync() {
    if (wx.getLaunchOptionsSync()) {
      return wx.getLaunchOptionsSync()
    } else {
      return _cacheAppOptions
    }
  },
  getRegisterStatus() {
    return new Promise(resolve => {
      wx.login({
        success(loginRes) {
          getRegisterStatusRequest.makeUrl().send({
            uid: loginRes.code
          }, function (res) {
            resolve(res)
          })
          //   .then(res => {
          //   resolve(res)
          // }).catch(e => {
          //   Route.redirectTo('landpage')
          // })
        }
      })
    })
  },
  launchApp(onSuccess, pageOptions) {
    console.log('pageOptions', pageOptions)

    let app = this

    // wx.hideTabBar()

    // wx.removeStorageSync('toPageLastUrl')
    //
    // wxe.checkSettingAuthed('userInfo').then(isAuthed => {
    //
    //   if (isFirst) {
    //     isFirst = false
    //     app.requestToken({
    //       loginType: 'first_login'
    //     }).then(res => {
    //       onSuccess && onSuccess(res)
    //     })
    //   } else {
    //     app.getRegisterStatus().then(res => {
    //       console.log('res', res)
    //       if (res.data) {
    //         let d = {
    //           reason: res.data.reason
    //         }
    //
    //         if (res.data.status < 0) {
    //
    //           app.requestToken().then(res => {
    //             onSuccess && onSuccess(res)
    //           })
    //
    //           return
    //         }
    //
    //         if (res.data.status == 0) {
    //           d.curStepIndex = 2
    //         }
    //         if (res.data.status == 1) {
    //           d.curStepIndex = 2
    //         }
    //         if (res.data.status == 2) {
    //           d.curStepIndex = 3
    //         }
    //         if (res.data.status == 3) {
    //           d.curStepIndex = 4
    //         }
    //
    //         WXPage.cache.set('register-status', d)
    //         Route.redirectTo(`register`, 'channel=true')
    //
    //       }
    //     })
    //   }
    //
    // })
  },
  globalData: {
    citys: []
  },
  trackMtjEvent(name) {
    let app = this
    if (app.mtj && app.mtj.trackEvent) {
      app.mtj.trackEvent(name)
    }
  },
  ...toastManager.methods,
  toPage(name, message = '', query = '', method = 'redirectTo') {
    console.log('call toPage', name)
    if (message) {
      console.warn(message)
    }
    let url =  `/pages/${name}/index`
    if (query) {
      url = url + '?' + query
    }
    let lastPage = getLastPage()
    wx.setStorageSync('toPageLastUrl', '/' + lastPage.$mp.href)
    wx[method]({
      url: url
    })
  },
  saveAuthInfo(info) {
    wx.setStorageSync('AuthInfo', info)
  },
  getProvinceCity(refresh = false, options = {}) {
    let app = this
    return new Promise(resolve => {
      let needRefresh = (!app.globalData.citys || app.globalData.citys.length < 1) || refresh
      console.log(needRefresh)
      if (needRefresh) {
        getProvinceCityRequest.makeUrl().send({}, function (res) {
          app.globalData.citys = res.data
          resolve(transformCitys(res.data, options))
        })
      } else {
        resolve(transformCitys(app.globalData.citys, options))
      }
    })
  },
  resolveSecondRequest(request) {
    let lastPage = getLastPage()
    if (lastPage) {
      if (lastPage.resolveSecondRequest) {
        lastPage.resolveSecondRequest(request)
      }
    }
  },
  firstLoginIndex(pageContext) {
    isFirst = true
    pageContext.$switchPage('index')
  },
  requestToken(queryData = {}) {
    let self = this
    return new Promise(async (resolve, reject) => {
      let wxLoginInfo = await $global.Auth.wxLogin()

      let _commonTokenQuery = encodeQueryData(queryData) || ''

      // 请求服务器token
      $global.Api.commonTokenCreate(wxLoginInfo.code, {}, {}, _commonTokenQuery).then(res => {

        if (!res || !res.hasOwnProperty('code')) {
          self.showToast('OtherRegisterError')
          reject(new OtherRegisterError())
        }

        if (res.code === 20000) {
          // 用户获取token成功
          // $global.Auth.setToken(res.data.token)
          resolve(res)
        } else {
          if (res.code === 61001) {
            // 61001 用户未注册
            Route.redirectTo(`landpage`)
          } else {
            // this.$set({
            //   debugerror: wxLoginInfo.code + ' ' + res.code + ' ' + JSON.stringify(res)
            // })
            console.log('other error', res)
          }
        }

      }).catch(e => {
        console.log('request failed', e, e.message)

        if (e && e.message) {
          console.log('has e.message', e.message)
          if (e.message.indexOf('61001') > -1) {
            console.log('redirectTo landpage')
            Route.redirectTo(`landpage`)
            return
          }
        }

        self.showToast(
          'request failed ' + (e ? e.errMsg : '')
        )
        if (e && e.errMsg && e.errMsg.indexOf('domain') > -1) {
          self.showToast('请求不在domain list里')
        } else {
          console.error('SAVE_TOKEN_FAIELD', '保存token失败: ' + (e ? e.message : ''))
          // 注册接口返回失败
          reject(new CreateTokenError())
        }
        // this.$set({
        //   debugerror: JSON.stringify(e)
        // })
      })
    })
  },
  listenPullDownRefresh(pageContext) {
    console.log('listenPullDownRefresh')
    let self = this
    return new Promise(resolve => {
      resolve()
      // self.checkIsRegistered(pageContext).then(() => {
      //   resolve()
      // })
    })
  },
  checkIsAuthed() {
    return new Promise(resolve => {
      wxe.checkSettingAuthed('userInfo').then(authedInfo => {
        let ret = authedInfo ? 'authed' : 'none'
        // console.log('checkIsAuthed', isUserInfoAuthed, ret)
        resolve(ret)
      })
    })
  },
  onError(e) {
    console.error('app catch error', e)
  },


})
